<template>
  <div class="setting-info">
    <div class="custom-title setting-info-title">
      <div>订单详情</div>
      <div>
        <!-- 订单为可以付款 -->
        <el-button v-if="order.isPay === 'Y'" class="link-button" color="#D6000F" @click="handleCommand('pay', order)"
          plain>{{ order.shopVo?.type === '2' ? '去提交' : '去付款'
          }}</el-button>
        <!-- 非零售订单 -->
        <el-button v-if="order.isShar === 'Y'" class="link-button" color="#D6000F" @click="handleCommand('share', order)"
          plain>分享订单模版</el-button>
        <!-- 订单为已发货 -->
        <el-button v-if="order.state === 'ck'" class="link-button" color="#D6000F"
          @click="handleCommand('confirm', order)" plain>确认收货</el-button>
        <!-- 订单为部分发货 -->
        <!-- <el-button v-if="order.state === 'bfck'" class="link-button" color="#D6000F"
                  @click="handleCommand('confirmPart', order)" plain>确认收货</el-button> -->
        <!-- 订单为自提 -->
        <el-button v-if="order.isCheck === 'Y'" class="link-button" color="#D6000F"
          @click="handleCommand('showCode', order)" plain>自提核销码</el-button>
        <!-- 订单为可以取消 -->
        <el-button v-if="order.isQx === 'Y'" class="link-button" @click="handleCommand('cancel', order)"
          plain>取消订单</el-button>
        <!-- 订单可以申请退款 -->
        <el-button v-if="order.isRefund === 'Y'" class="link-button" color="#D6000F"
          @click="handleCommand('refund', order)" plain>申请退款</el-button>
      </div>
    </div>
    <div class="setting-info-box" :loading="infoLoading">
      <el-row :gutter="10" class="list-header">
        <el-col :span="5">
          <div class="item-th" style="text-align: left;padding-left: 30px;">商品</div>
        </el-col>
        <el-col :span="10">
          <div class="item-th">商品名称</div>
        </el-col>
        <el-col :span="3">
          <div class="item-th">商品单价</div>
        </el-col>
        <el-col :span="3">
          <div class="item-th">商品数量</div>
        </el-col>
        <el-col :span="3">
          <div class="item-th">金额小计</div>
        </el-col>
      </el-row>
      <div class="order">
        <div class="order-header">
          <div class="order-info" style="display: flex;justify-content: space-between;">
            <div style="display: flex;align-items: center;">
              <div class="order-shop__img"><el-avatar shape="square" :size="22" :src="order?.shopVo?.pic || ''" /></div>
              <div class="order-shop__title">{{ order?.shopVo?.name }}</div>
              <div class="order-time">{{ $timeDisplay('', '', order.ctime) }}</div>
              <div class="order-number">订单号：{{ order.orderCode }}</div>
            </div>
            <div class="order-state">订单状态：{{ order.stateDisplay }}</div>
          </div>
        </div>
        <el-row :gutter="10" class="order-body" v-for="goods in order.sellVos" :key="goods.id" align="middle">
          <el-col :span="5">
            <div class="item-td">
              <el-image style="width: 128px; height: 128px; background-color: #fff;" :src="goods.img" fit="cover" />
            </div>
          </el-col>
          <el-col :span="10">
            <div class="item-td" style="text-align: left;">{{ goods.name }}</div>
          </el-col>
          <el-col :span="3">
            <div class="item-td">{{ $numberPriceDisplay(goods.oneprice) }}</div>
          </el-col>
          <el-col :span="3">
            <div class="item-td">{{ goods.count }}</div>
          </el-col>
          <el-col :span="3">
            <div class="item-td">{{ $numberPriceDisplay(goods.computedprice) }}</div>
          </el-col>
        </el-row>
        <div class="order-header">
          <div class="order-info">
            <div class="order-pay" style="text-align: left;">订单来源：{{ order.typeDisplay }}</div>
            <div class="order-pay">支付方式：{{ order.payTypeDisplay }}</div>
            <div class="order-pay" style="text-align: right;">实付金额：<span class="order-count">{{
              $numberPriceDisplay(order.totalPrice) }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="order-invoices" v-if="order?.invoices?.length">
        <div class="order-invoices__title">物流信息</div>
        <div style="width: 100%;margin-top: 20px;">
          <el-row :gutter="10" class="list-header">
            <el-col :span="4">
              <div class="item-th">物流单号</div>
            </el-col>
            <el-col :span="4">
              <div class="item-th">物流公司</div>
            </el-col>
            <el-col :span="4">
              <div class="item-th">发货时间</div>
            </el-col>
            <!-- <el-col :span="2">
              <div class="item-th">签收状态</div>
            </el-col>
            <el-col :span="4">
              <div class="item-th">签收时间</div>
            </el-col> -->
            <el-col :span="9">
              <div class="item-th">发货商品/数量</div>
            </el-col>
            <el-col :span="3">
              <div class="item-th">操作</div>
            </el-col>
          </el-row>
        </div>
        <div style="width: 100%;">
          <el-row :gutter="10" v-for="invoice in order.invoices" :key="invoice.id" class="list-row">
            <el-col :span="4">
              <div class="item-td">{{ invoice.freightBillNo }}</div>
            </el-col>
            <el-col :span="4">
              <div class="item-td">{{ invoice.freightName }}</div>
            </el-col>
            <el-col :span="4">
              <div class="item-td">{{ $timeDisplay('', '', invoice.ctime) }}</div>
            </el-col>
            <!-- <el-col :span="2">
              <div class="item-td">{{ invoice.signStatus === 'Y' ? '已经签收' : '未签收' }}</div>
            </el-col>
            <el-col :span="4">
              <div class="item-td">{{ $timeDisplay('', '', invoice.utime) }}</div>
            </el-col> -->
            <el-col :span="9">
              <div class="item-td">
                <div v-for="d in invoice.detailInfoVos" :key="d.id">{{ d.skuName }} / {{ d.qty || 0
                  }}</div>
              </div>
            </el-col>
            <el-col :span="3">
              <div class="item-td">
                <el-button class="link-button" @click="handleCommand('logistics', invoice)" plain>物流详情</el-button>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="order-refundInfo" v-if="order.refundId && order.refundInfoVo.status === 'N'">
        <div class="order-refundInfo__title">退款信息</div>
        <div class="order-refundInfo__body">
          <div class="order-refundInfo__body--item">退款单号：{{ order.refundId }}</div>
          <div class="order-refundInfo__body--item">退款状态：{{ refundOrderStatusMap[order.refundInfoVo.status] }}</div>
          <div class="order-refundInfo__body--item">退款备注：<span style="color: red">{{ order.refundInfoVo.response
              }}</span></div>
        </div>
      </div>
      <div class="order-address">
        <div class="order-address__title">收货信息</div>
        <div class="order-address__info">收货地址：{{ addressDisplay(order) }} <br>收货人：{{ order.consignorName }} <br>收货电话：{{
          order.phone }}</div>
      </div>
    </div>
    <refundForm ref="dataFormRef" @change="bindChangeInfo"></refundForm>
    <confirmForm ref="dataConfirmFormRef" @change="bindChangeInfo"></confirmForm>
    <custom-dialog title="物流详情" width="900px" custom-class="custom-web" v-model="state.isVisible"
      :disabled="state.disabled" @close="handleCommand('close', $event)">
      <el-card v-loading="state.loading" style="max-width: 100%" shadow="never">
        <template #header>
          <div class="card-header">
            <el-avatar :size="38" :src="state.logistics.logo" style="margin-right: 10px;" /> <span> {{
              state.logistics.typename }} {{
                state.logistics.number
              }}</span>
          </div>
        </template>
        <el-timeline v-if="state.logistics.list.length"
          style="max-width: 100%; padding-left: 0px; --el-text-color-secondary: #323232;--el-font-size-small: 14px;--el-text-color-primary: #999999">
          <el-timeline-item v-for="(item, index) in state.logistics.list" :key="index" :timestamp="item.time"
            placement="top">
            {{ item.status }}
          </el-timeline-item>
        </el-timeline>
        <el-empty v-else description="暂无物流信息" />
      </el-card>
    </custom-dialog>
  </div>
</template>

<script setup name="orderDetail">
import { appOrderByIdGet, appOrderQxGet, appOrderGetInvoiceMsgGet, appOrderOverPost } from '@/api/order'
import { dialogCustomStyle } from '@/components/webCustom/utils'
import { orderStateMap, orderTypeMap, orderPayTypeMap, refundOrderStatusMap, addressDisplay } from './components/orderHelp'
import useClipboard from 'vue-clipboard3'
import refundForm from './components/refundForm'
import confirmForm from './components/confirmForm'
const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
const dataFormRef = ref(null)
const dataConfirmFormRef = ref(null)
const infoLoading = ref(true)
const order = ref({}) // 订单信息
const state = reactive({
  isVisible: false,
  disabled: true,
  loading: false,
  logistics: {
    aflg: '', // 状态 boolean
    time: '', // 签收时间 string
    deliverystatus: 0, // 快递状态 1在途中 2派件中 3已签收 4派送失败(拒签等) number
    error: '', // 失败原因 string
    issign: 0, // 是否签收 number
    list: [], // ExpressDetail list
    logo: '', // 快递公司Logo string
    number: '', // 快递单号 string
    type: '', // 快递公司代码 string
    typename: '' // 快递公司名称 string
  },
})
function getOrderInfo () {
  appOrderByIdGet({ params: { id: route.params.id } }).then((res) => {
    console.log(res)
    const data = res.data

    data.stateDisplay = data.state === 'xd' && data.shopVo.type === '2' ? '待提交' : orderStateMap[data.state]
    data.typeDisplay = orderTypeMap[data.type]
    data.payTypeDisplay = orderPayTypeMap[data.payType]
    data.payTo = { name: 'orderPayment', params: { id: data.id } }
    order.value = data
  }).catch((err) => {
    console.log(err)
  }).finally(() => {
    infoLoading.value = false
  })
}
route.params.id && getOrderInfo()
const bindChangeInfo = (v) => {
  getOrderInfo()
}

const { toClipboard } = useClipboard()
function handleCommand (command, r) {
  switch (command) {
    case 'pay': // 去付款
      router.push(r.payTo)
      break
    case 'share': // 分享订单模版
      const link = `${location.origin}/${import.meta.env.VITE_APP_HISTORY === 'history' ? '' : '#/'}share/${r.id}`
      proxy.$modal.confirm(
        `<div style="font-weight: bold;font-size: 16px;color: #323232;line-height: 21px;">订单模板分享链接</div><div style="background-color: #F5F6F5;font-size: 16px;color: #323232;line-height: 21px;padding: 12px 18px;margin-top: 14px;">${link}</div>`,
        { title: "分享订单模板链接", type: '' },
        {
          dangerouslyUseHTMLString: true,
          draggable: true,
          customClass: 'custom-message-box',
          customStyle: dialogCustomStyle({ width: '572px' }),
          showClose: false,
          confirmButtonText: '复制链接',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confirmButtonText = '复制中...'
              toClipboard(link).then(flag => {
                console.log(flag)
                proxy.$modal.msgSuccess(`链接已复制成功`)
                done()
                setTimeout(() => {
                  instance.confirmButtonLoading = false
                }, 300)
              }).catch(e => {
                console.log(e)
                proxy.$modal.msgError('链接已复制失败，请手动复制')
                instance.confirmButtonLoading = false
              })
            } else {
              done()
            }
          }
        }
      ).catch((err) => { console.log(err) })
      break
    case 'confirm': // 确认收货
      // dataConfirmFormRef.value.show()
      // dataConfirmFormRef.value.$nextTick(() => {
      //   dataConfirmFormRef.value.setDefault({ id: r.id }, r)
      // })
      proxy.$modal.confirm('<div style="display: flex;flex-direction: column;word-break: break-all;align-items: center;font-weight: bold;font-size: 18px;color: #323232;line-height: 21px; text-algin">您确定要对编号【' + r.orderCode + '】订单进行【确认收货】操作吗？</div>', { title: '温馨提示' }, {
        type: '',
        dangerouslyUseHTMLString: true,
        draggable: true,
        customClass: 'custom-message-box',
        customStyle: dialogCustomStyle({ width: '385px' }),
        showClose: false,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '确认中...'
            appOrderOverPost({ body: { id: r.id } }).then((res) => {
              if (res.code === 0) {
                proxy.$modal.msgSuccess("确认成功！");
                done()
                getList()
              } else {
                proxy.$modal.msgError(res.msg);
              }
            }).finally(() => {
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      }).then(action => {
        console.log('confirm', action)
      }).catch(action => {
        console.log('cancel', action)
      })
      break
    case 'confirmPart': // 确认收货(部分发货)
      // TODO 确认收货(部分发货) 暂时不做处理
      break
    case 'showCode': // 自提二维码
      const checkCode = r.checkCode
      proxy.$modal.confirm(`<div style="display: flex;flex-direction: column;align-items: center;font-weight: bold;font-size: 40px;color: #323232;line-height: 21px; text-algin">${checkCode}</div>`,
        { title: '自提核销码' },
        {
          type: '',
          confirmButtonText: '复制',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          draggable: true,
          customClass: 'custom-message-box',
          customStyle: dialogCustomStyle({ width: '385px' }),
          showClose: false,
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confirmButtonText = '复制中...'
              toClipboard(checkCode).then(flag => {
                console.log(flag)
                proxy.$modal.msgSuccess(`自提核销码已复制成功`)
                done()
                setTimeout(() => {
                  instance.confirmButtonLoading = false
                }, 300)
              }).catch(e => {
                console.log(e)
                proxy.$modal.msgError('自提核销码复制失败，请手动复制')
                instance.confirmButtonLoading = false
              })
            } else {
              done()
            }
          }
        }).then(action => {
          console.log('confirm', action)
        }).catch(action => {
          console.log('cancel', action)
        })
      break
    case 'cancel': // 取消订单
      proxy.$modal.confirm('<div style="display: flex;flex-direction: column;word-break: break-all;align-items: center;font-weight: bold;font-size: 18px;color: #323232;line-height: 21px; text-algin">您确定要对编号【' + r.orderCode + '】订单进行取消操作吗？</div>', { title: '温馨提示' }, {
        type: '',
        dangerouslyUseHTMLString: true,
        draggable: true,
        customClass: 'custom-message-box',
        customStyle: dialogCustomStyle({ width: '385px' }),
        showClose: false,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '取消中...'
            appOrderQxGet({ params: { id: r.id } }).then((res) => {
              if (res.code === 0) {
                proxy.$modal.msgSuccess("取消成功！");
                done()
                getList()
              } else {
                proxy.$modal.msgError(res.msg);
              }
            }).finally(() => {
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      }).then(action => {
        console.log('confirm', action)
      }).catch(action => {
        console.log('cancel', action)
      })
      break
    case 'refund': // 申请退款
      dataFormRef.value.show()
      dataFormRef.value.$nextTick(() => {
        const { id, totalPrice, refundId, refundInfoVo } = r
        dataFormRef.value.setDefault(!refundId || (refundInfoVo && refundInfoVo.status === 'N') ? { id, applyAmount: totalPrice } : {
          id,
          rid: refundId,
          applyAmount: totalPrice,
          description: refundInfoVo ? refundInfoVo.description : '',
          evidence: refundInfoVo ? refundInfoVo.evidence : '',
          reason: refundInfoVo ? refundInfoVo.reason : '',
          skuTitle: refundInfoVo ? (refundInfoVo.skuTitle || '') : '',
          skuNo: refundInfoVo ? (refundInfoVo.skuNo || '') : '',
          skuCout: refundInfoVo ? (refundInfoVo.skuCout || '') : ''
        }, r)
      })
      break
    case 'detail': // 查看详情
      router.push(r.to)
      break
    case 'logistics': // 物流详情
      state.isVisible = true
      state.loading = true
      appOrderGetInvoiceMsgGet({
        params: { // systemOrderGetInvoiceMsgGet 请求参数对象
          invoiceId: r.id // 物流id string-query
        }
      }).then(res => {
        if (!res.code) {
          if (!res.data.deliverystatus) {
            state.logistics.list = []
            state.logistics.logo = ''
            state.logistics.time = r.ctime
            state.logistics.number = r.freightBillNo
            state.logistics.typename = r.freightName
          } else {
            res.data.time = r.ctime
            state.logistics = res.data
          }
        }
      }).finally(() => {
        state.loading = false
      })
      break
    case 'close': // 物流详情
      state.isVisible = false
      break
    default:
      proxy.$modal.msgSuccess("敬请期待！");
      break;
  }
}
</script>

<style lang="scss" scoped>
.setting-info {
  width: 100%;

  &-title {
    font-size: var(--jbc-font-size-extra-large);
    display: flex;
    justify-content: space-between;
  }

  .setting-info-box {
    margin-top: 20px;
  }
}


.list-header {
  background: #F8F8F8;
  border-radius: 8px;

  .item-th {
    font-weight: bold;
    font-size: var(--jbc-font-size-medium);
    color: var(--jbc-font-color);
    line-height: 22px;
    padding: 16px 0;
    text-align: center;
  }
}

.order {
  margin-top: 10px;

  &-box {
    min-height: 220px;
  }

  &-header {
    margin-left: -5px;
    margin-right: -5px;
    padding: 11px 15px;
    background: #F8F8F8;
    border: 1px solid #EBEBEB;
  }

  &-info {
    display: flex;
    align-items: center;
    font-weight: bold;
    font-size: 14px;
    color: #323232;
    line-height: 19px;
  }

  &-shop__img {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  &-shop__title {
    margin-left: 10px;
  }

  &-time {
    margin-left: 10px;
  }

  &-number {
    margin-left: 10px;
    color: #666666;
  }

  &-pay {
    flex: 1;
    text-align: center;
  }

  &-count {
    color: var(--jbc-color);
    font-weight: bold;
    font-size: var(--jbc-font-size-extra-large);
  }

  &-body {
    border: 1px solid #EBEBEB;

    .item-td {
      font-size: 18px;
      color: #666666;
      line-height: 24px;
      text-align: center;
      padding: 19px 0;

      &.goods-list {
        padding-left: 14px;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
      }

      .goods-info {
        width: 130px;
        height: 130px;
        background: #FFFFFF;
        border: 1px solid #EBEBEB;
        position: relative;

        &~.goods-info {
          margin-left: 10px;
        }
      }

      .goods-other {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 12px;
        color: #fff;
        background-color: rgba(0, 0, 0, 0.5);
        padding: 0 5px;
        position: absolute;
        z-index: 1;
        left: 0;
        right: 0;
        bottom: 0;
      }

      &.td-opt {
        display: flex;
        flex-direction: column;
      }

      .link-button {
        &~.link-button {
          margin-top: 10px;
          margin-left: 0;
        }
      }
    }
  }
}

.order-address {
  margin-top: 40px;
  margin-right: -4px;
  margin-left: -4px;

  &__title {
    font-weight: bold;
    font-size: var(--jbc-font-size-extra-large);
    color: var(--jbc-font-color);
    line-height: 19px;
  }

  &__info {
    margin-top: 16px;
    padding: 16px 20px;
    border: 1px solid #EBEBEB;
    font-size: var(--jbc-font-size-medium);
    color: var(--jbc-font-color-light);
    line-height: 32px;
  }

}

.order-invoices {
  margin-top: 40px;
  margin-right: -4px;
  margin-left: -4px;

  &__title {
    font-weight: bold;
    font-size: var(--jbc-font-size-extra-large);
    color: var(--jbc-font-color);
    line-height: 19px;
  }

  .list-header {
    background: #F8F8F8;
    border-radius: 8px;

    .item-th {
      font-weight: bold;
      font-size: var(--jbc-font-size-medium);
      color: var(--jbc-font-color);
      line-height: 22px;
      padding: 16px 0;
      text-align: center;
    }
  }

  .list-row {
    .item-td {
      font-size: 18px;
      color: #666666;
      line-height: 24px;
      text-align: center;
      padding: 19px 0;

      &.td-opt {
        display: flex;
        flex-direction: column;
      }
    }
  }
}

.order-refundInfo {
  margin-top: 40px;
  margin-right: -4px;
  margin-left: -4px;

  &__title {
    font-weight: bold;
    font-size: var(--jbc-font-size-extra-large);
    color: var(--jbc-font-color);
    line-height: 19px;
  }

  &__body {
    margin-top: 16px;
    padding: 16px 20px;
    border: 1px solid #EBEBEB;
    font-size: var(--jbc-font-size-medium);
    color: var(--jbc-font-color-light);
    line-height: 32px;
  }
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
  color: #323232;
  line-height: 21px;
}
</style>